var fs=require('fs');
var gd=require('gd');

/*****************************************************************************/
function loadFile(space,fg,filename,custompath,fallback)
{
	if (filename!=undefined && filename.match(/\.\./)) throw "File error";
	var tmpltext;
	var basepath1=space.site.paths[fg];
	var basepath2=space.system.paths[fg];
	var f;
	if (filename) {
		if (custompath) {
			f=new fs.File(basepath1+custompath+"/"+filename);
			if (f.isFile()) {
				f.open("r");
				tmpltext=f.read().toString('utf-8');
				f.close();
				return tmpltext;
			}
		}
		f=new fs.File(basepath1+filename);
		if (f.isFile()) {
			f.open("r");
			tmpltext=f.read().toString('utf-8');
			f.close();
			return tmpltext;
		}
	}
	if (!fallback) fallback=filename;
//	"/pagetemplates/new.html");
	var f=new fs.File(basepath2+fallback);
	if (!f.isFile()) return "";
	f.open("r");
	tmpltext=f.read().toString('utf-8');
	f.close();
	return tmpltext;
}

/*****************************************************************************/
function saveFile(space,fg,filename,tmpltext)
{
	if (filename.match(/\.\./)) throw "File error";
	var basepath1=space.site.paths[fg];
	var f1=new fs.File(basepath1+filename);
	var oldtext;
	if (f1.isFile()) {
		try {
			f1.open("r");
			oldtext=f1.read().toString('utf-8');
			f1.close();
		} catch (e) {
			throw "admin_templates.js: saveFile() - can not read file, fg="+fg+", filename="+filename;
		}
	}
	if (oldtext!=undefined && oldtext==tmpltext) return;
	if (oldtext!=undefined) {
		var nameparts=filename.match(/^(.+\/)(.+)$/);
		if (!nameparts) nameparts=["","",filename];
		var d1=new fs.Directory(basepath1+nameparts[1]+".backup");
		if (!d1.isDirectory()) {
			try {
				d1.create();
			} catch (e) {
				throw "admin_templates.js: saveFile() - can not create directory, fg="+fg+", filename="+filename+", dir="+basepath1+nameparts[1]+".backup";
			}
		}
		var fn=0;
		var f2;
		do {
			fn++;
			f2=new fs.File(basepath1+nameparts[1]+".backup/"+nameparts[2]+"-"+fn);
		} while (f2.isFile());
		try {
			f2.open("w");
			f2.write(oldtext);
			f2.close();
		} catch (e) {
			throw "admin_templates.js: saveFile() - can not save backup file, fg="+fg+", filename="+filename;
		}
	}
	try {
		space.functions.mkdir_rec(basepath1,filename,1);
	} catch(e) {
		throw "admin_templates.js: saveFile() - can not create directory, fn='"+basepath1+filename+"'\n"+e;
	}
	try {
		f1.open("w");
		f1.write(tmpltext);
		f1.close();
	} catch (e) {
		throw "admin_templates.js: saveFile() - can not save file, fn='"+basepath1+filename+"'\n"+e;
	}
}

/*****************************************************************************/
function listTemplatesRecurse(space,basepath,h,val,exts,path)
{
	if (basepath.charAt(basepath.length-1)!="/") basepath+="/";
	if (path==undefined) path="";
	var d=new fs.Directory(basepath+path);
	if (!d.exists()) return;
	d.listDirectories().forEach(function(x) {
		if (x.charAt(0)==".") return;
		if (x=="_models") return;
		if (x=="shared") return;
		listTemplatesRecurse(space,basepath,h,val,exts,path+x+"/");
	});
	d.listFiles().forEach(function(x) {
		if (x=="_auto.js") return;
		if (!exts) {
			h[path+x]=val;
		} else {
			var a=x.match(/\.(\w+)$/);
			if (a) {
				if (exts[a[1].toLowerCase()]) h[path+x]=val;
			}
		}
	});
}

/*****************************************************************************/

exports.controllers={
	/*************************************************************************/
	admin_templates: function(space) {
		if (!space.roles.templates) return "Access denied";
		var mode=space.fields.mode||"list";
		return space.controllers['admin_templates__'+mode](space);
	},
	
	/*************************************************************************/
	admin_templates__list: function(space) {
		space.templates=space.site.sql.execute_and_fetch("templates/list_for_panel");
		return space.views.process("widgets/admin_templates/list",space);
	},
	
	/*************************************************************************/
	admin_templates__edit: function(space) {
		if (space.fields.template_id) {
			space.template=space.site.sql.execute_and_fetch_one("templates/get");
			space.template_places=space.site.sql.execute_and_fetch("template_places/list");
		} else {
			space.template={};
			space.template_places=[];
		}
		space.template_place_types=space.site.sql.execute_and_fetch("template_place_types/list");
		
		space.template.tmpltext=loadFile(
			space,
			"views",
			space.fields.template_id?"/pagetemplates/"+space.fields.template_id+".html":undefined,
			undefined,
			"/pagetemplates/new.html"
		);
		return space.views.process("widgets/admin_templates/edit",space);
	},
	
	/*************************************************************************/
	admin_templates__save: function(space) {
		if (space.fields.template_id && space.fields.template_id!="") {
			space.site.sql.execute("templates/update");
		} else {
			space.site.sql.execute("templates/insert");
			space.fields.template_id=space.site.sql.execute_and_fetch_one("templates/max_id")['id'];
		}
		var hashes=space.functions.parse_grids(space).places;
		space.functions.save_grid(space,hashes,"template_places",{
			existing: function(hash,id) {return {}},
			insert: function(hash,id) {},
			update: function(hash,id) {hash.template_place_id=id;},
			delold: function(hash,id) {hash.template_place_id=id;}
		});
		saveFile(space,"views","/pagetemplates/"+space.fields.template_id+".html",space.fields.tmpltext)
		return JSON.stringify({redirect:{url:space.action}});
	},
	
	/*************************************************************************/
	admin_templates__delete: function(space) {
		space.template=space.site.sql.execute_and_fetch_one("templates/get");
		return space.views.process("widgets/admin_templates/delete",space);
	},
	
	/*************************************************************************/
	admin_templates__delete_save: function(space) {
		space.site.sql.execute("template_places/delete_of_template");
		space.site.sql.execute("templates/delete");
		return JSON.stringify({redirect:{url:space.action}});
	},

	/*************************************************************************/
	admin_alltemplates: function(space) {
		if (!space.roles.templates) return "Access denied";
		var mode=space.fields.mode||"list";
		return space.controllers['admin_alltemplates__'+mode](space);
	},

	/*************************************************************************/
	admin_alltemplates__list: function(space) {
		space.fsfiles=[];
		var fgs=[
			{path: "views", name: "view",exts: undefined},
			{path: "sql", name: "SQL query", exts: {sql:1}},
			{path: "controllers", name: "Controllers", exts: {js:1}},
			{path: "html", name: "Client JS", exts: {js:1}},
			{path: "i18n", name: "Internationalization", exts: {js:1,nosystem:1}},
			{path: "html", name: "CSS", exts: {css:1}}
		];
		fgs.forEach(function(fg) {
			var h;
			h={};
			if (!fg.nosystem) listTemplatesRecurse(space,space.system.paths[fg.path],h,1,fg.exts);
			listTemplatesRecurse(space,space.site.paths[fg.path],h,2,fg.exts);
			var tmpa=[];
			for (var k in h) tmpa.push(k);
			tmpa.sort();
			tmpa.forEach(function(k) {
				space.fsfiles.push({
					file:k,
					name:"",
					type:fg.name,
					path: fg.path,
					overrided: h[k]==2?1:0
				});
			});
		});
		return space.views.process("widgets/admin_fsfiles/list",space);
	},
	
	/*************************************************************************/
	admin_alltemplates__edit_ajaj: function(space) {
		var fsf=space.fields.fsfile.match(/^(\w+)@(.+)$/);
		space.data=loadFile(space,fsf[1],fsf[2]);
		space.file=fsf[2];
		space.type=fsf[1];

		var syntax=fsf[2].match(/\.(\w+)/)[1];
		return JSON.stringify({file:fsf[2],type:fsf[1],data:space.data,syntax:syntax,call:"load_code2"});
//		return space.views.process("widgets/admin_fsfiles/edit",space);
	},
	/*************************************************************************/
	admin_alltemplates__edit: function(space) {
		var fsf=space.fields.fsfile.match(/^(\w+)@(.+)$/);
		space.data=loadFile(space,fsf[1],fsf[2]);
		space.file=fsf[2];
		space.type=fsf[1];

		space.syntax=fsf[2].match(/\.(\w+)/)[1];
		return space.views.process("widgets/admin_fsfiles/edit",space);
	},
	
	/*************************************************************************/
	admin_alltemplates__save: function(space) {
		var fsf=space.fields.fsfile.match(/^(\w+)@(.+)$/);
		saveFile(space,fsf[1],fsf[2],space.fields.data);
		return "{ok:1}";
	}

	/*************************************************************************/
};

/*****************************************************************************/
